//
//  CZOauthViewController.swift
//  01-sinaWeibo-05-09
//
//  Created by mac on 16/5/14.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

import SVProgressHUD

class CZOauthViewController: UIViewController {
    
    override func loadView() {
        view = webView
        webView.delegate = self
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.view.backgroundColor = GlobalBKGColor
        //设置导航栏
        //右边
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        //左边
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "填充", style: UIBarButtonItemStyle.Plain, target: self, action: "autoFill")
        
        //中间title
        navigationItem.title = "登录"
        //使用WebView加载页面
        //https://api.weibo.com/oauth2/authorize?client_id=1967441000&redirect_uri=http://www.baidu.com/
        let urlString = oauthURLString + "?client_id=" + client_id + "&redirect_uri=" + redirect_uri
        let url = NSURL(string: urlString)
        let request = NSURLRequest(URL:url!)
        webView.loadRequest(request)
        // 进度形式,如果不主动关闭,会一直存在
        SVProgressHUD.showWithStatus("正在玩命加载中...")
        

    }
    //MARK: - 点击事件
    //登录
   @objc private func autoFill()
    {
        let jsString = "document.getElementById('userId').value='13751993546';document.getElementById('passwd').value='he13533114263';"
        //使用WebView执行JS代码
        webView.stringByEvaluatingJavaScriptFromString(jsString)
    }
    //取消
    @objc private func close()
    {
      //SVProgressHUD.dismiss()
      dismissViewControllerAnimated(true, completion: nil)
        //如果没有网络 一直加载 点击取消 也要关闭
        SVProgressHUD.dismiss()
        
    }
    
    //MARK: --懒加载
    //wedView
    private lazy var webView:UIWebView = UIWebView()
    
    
}

extension CZOauthViewController :UIWebViewDelegate
{
    //当WebView加载完成时调用
    func webViewDidFinishLoad(webView: UIWebView) {
       
        SVProgressHUD.dismiss()
    }
    
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        let url = request.URL!
        CZPrint(items: "request\(url.absoluteString)")
        //requesthttps://api.weibo.com/oauth2/authorize?client_id=1967441000&redirect_uri=http://www.baidu.com/
        if !url.absoluteString.hasPrefix(redirect_uri)
        {
            //只要不是授权回调地址  是新浪的界面就让他去加载
            return true
        }else
        {
            // 是授权回调地址,点击的是取消或授权,不让他去加载,我们自己来做一些事情
            // URL的query: ?后面的东西
            let query = url.query!
            CZPrint(items: "query:\(query)")
            let codeString = "code="
            if query.hasPrefix(codeString)
            {
                // 如果query 是以 code=开头表示点击的授权按钮
                // 从query中截取code的值,substringFromIndex从指定位置截取到最后
                let code = (query as NSString).substringFromIndex(codeString.characters.count)
                CZPrint(items: "code: \(code)")
                CZUserAccountViewModel.sharedInstance.loadAccessToken(code, callback: { (error) -> () in
                    if error != nil{
                        CZPrint(items: "出现错误了:\(error)")
                        SVProgressHUD.showErrorWithStatus("您的网络不给力....")
                        
                        //延迟1秒关闭
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1*NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                            self.close()
                        })
                    }else
                    {
                        
                        //没有错
                        self.close()
                        //更改window的根控制器
                        
                    }
                })

                
            }else
            {
                //点击了取消
                close()
            }
            return false
        }
        
        
    }
}







